let loadClose = null;
let hasGuided = false;
let docmentScroll = false;

setInterval(() => {
  if (!docmentScroll) {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }
}, 50);

if ('serviceWorker' in navigator) {
  // window.addEventListener('beforeinstallprompt', (e) => {
  //   console.log('beforeinstallprompt');
  //   // 阻止自动显示安装提示
  //   e.preventDefault();
  //   // 保存事件以便稍后触发
  //   window.deferredPrompt = e;
  // });

  window.addEventListener('load', () => {
    navigator.serviceWorker
      .register('/sw.js')
      .then((registration) => {
        console.log('Service Worker registered successfully.', registration);
      })
      .catch((error) => {
        console.error('Service Worker registration failed:', error);
      });
  });
}
window.onload = () => {
  addManifest();
  addComments();
  addApps();
  document.querySelectorAll('.install-btn').forEach(d => d.addEventListener('click', install));
  document.querySelector('.loading-overlay')?.setAttribute('style', 'display:none;');
  docmentScroll = true;
};

function install() {
  console.log('执行了');
  const key = 'WEBLOGGER_CUSTOM_INCREAMENT_ID_KEY';
  const result = localStorage.getItem(key);
  localStorage.setItem(key, Number(result) + 1);

  if (loadClose && !isCanDownloadApp())
    return;

  // TG环境 Tengine
  if (isTg()) {
    return;
  }

  // TODO IOS 环境 引导
  if (isIOS()) {
    return;
  }

  // 环境不支持时
  if (!isCanDownloadApp() && !hasGuided) {
    loadClose = createProgressPopup((pro) => {
      if (hasGuided && loadClose) {
        loadClose();
        loadClose = null;
        install();
      }
      if (isCanDownloadApp() || pro >= 100) {
        hasGuided = true;
        return;
      }
      install();
    });
    return;
  }
  if (!isCanDownloadApp()) {
    // TODO 引导
    console.log('打开引导');
    return;
  }

  installWebApp(() => {});
}

function addManifest() {
  const searchParams = new URLSearchParams(location.search);
  const source = searchParams.get('source') || '';
  // 请求manifest.json文件
  const manifestHref = '/manifest.json';
  const linkElement = document.createElement('link');
  linkElement.rel = 'manifest';
  if (source) {
    linkElement.href = `${manifestHref}?source=${source}`;
  }
  else {
    linkElement.href = manifestHref;
  }
  document.head.appendChild(linkElement);
}

function installWebApp(successCallback?: () => void, cancalCallback?: () => void) {
  // 检测环境
  if (isPwa()) {
    return;
  }

  console.log('等待用户选择');
  // 显示安装提示
  window.deferredPrompt.prompt();
  // 等待用户选择
  window.deferredPrompt.userChoice.then((choiceResult) => {
    if (choiceResult.outcome === 'accepted') {
      successCallback?.();
    }
    else {
      cancalCallback?.();
    }
    window.deferredPrompt = null;
  });
}

function isPwa() {
  const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
  const isIOSStandalone = window.navigator?.standalone === true;
  return isStandalone || isIOSStandalone;
}

function isCanDownloadApp() {
  return !!window.deferredPrompt;
}

function isTg() {
  return typeof Telegram !== 'undefined' || !!window?.TelegramWebviewProxy;
}

function isIOS() {
  return /iphone|ipad|ipod/i.test(navigator.userAgent);
}

function addComments() {
  const dom = document.querySelector('.comments');
  if (!dom)
    return;
  const data = [
    {
      avatar: '/imgs/pwa/avatar-1.webp',
      name: 'Lara Liras',
      time: '5 de setembro de 2024',
      content: 'O jogo é bom , mais precisa de um incentivo, no geral eu gostei bastante Dá pra pessoa distrair e jogar é muito saudável ! Amei os porquinhos kkk',
      useful: 249,
    },
    {
      avatar: '/imgs/pwa/avatar-2.webp',
      name: 'Angelita Da Silva',
      time: '19 de agosto de 2024',
      content: 'Gosto muito, o jogo é super divertido e o jackpot explode todos os dias',
      useful: 249,
    },
    {
      avatar: '/imgs/pwa/avatar-3.webp',
      name: 'Rubens Vieira dos Santos',
      time: '9 de junho de 2024',
      content: 'muito divertido e não fica trancando e cheio de anúncios muito bom mesmo',
      useful: 249,
    },
  ];
  let html = ``;

  data.forEach((d) => {
    html += `  <div class="grid text-sm text-black text-left mt-4">
          <div class="flex items-center">
            <img class="w-8 rounded-full object-fill mr-4" src="${d.avatar}" alt="" />
            <div class="mr-auto text-base text-gray-500">${d.name}</div>
            <img src="/imgs/pwa/more.svg" alt="" srcset="" class="w-5" />
          </div>
          <div class="flex items-center text-sm my-4">
            <img src="/imgs/pwa/star.svg" alt="" srcset="" class="mr-2 w-3" />
            <img src="/imgs/pwa/star.svg" alt="" srcset="" class="mr-2 w-3" />
            <img src="/imgs/pwa/star.svg" alt="" srcset="" class="mr-2 w-3" />
            <img src="/imgs/pwa/star.svg" alt="" srcset="" class="mr-2 w-3" />
            <img src="/imgs/pwa/star.svg" alt="" srcset="" class="mr-2 w-3" />
            <span class="text-gray-600">${d.time}</span>
          </div>
          <div class="text-gray-500">
              ${d.content}
          </div>
          <div class="text-gray-600 mt-4">Essa avaliação foi marcada como útil por ${d.useful} pessoas</div>
          <div class="flex items-center text-gray-600 mt-4">
            <span>Você achou isso útil?</span>
            <div class="mx-4 border border-gray-200 border-solid rounded-full px-4">Sim</div>
            <div class="border border-gray-200 border-solid rounded-full px-4">Não</div>
          </div>
        </div>`;
  });
  dom.innerHTML = html;
}

function addApps() {
  const dom = document.querySelector('.apps');
  if (!dom)
    return;
  const data = [
    {
      pic: '/imgs/pwa/img-1.png',
      name: 'Cash Craze: Casino Slots Games',
      describe: 'Casual Joy Games',
      score: '4,5',
    },
    {
      pic: '/imgs/pwa/img-2.png',
      name: 'Charge Buffalo Slot-TaDa Jogos',
      describe: 'FUFAFA TECHNOLOGY LTD CO.',
      score: '4,5',
    },
    {
      pic: '/imgs/pwa/img-3.png',
      name: 'Jackpot Magic Slots',
      describe: 'Big Fish Games',
      score: '4,5',
    },
    {
      pic: '/imgs/pwa/img-4.png',
      name: 'Diamond Slot - Slot Game',
      describe: 'International Games System Co.,Ltd.',
      score: '3,9',
    },
    {
      pic: '/imgs/pwa/img-5.png',
      name: 'Bônus Bingo Cassino-TaDa Jogo',
      describe: 'FUFAFA TECHNOLOGY LTD CO.',
      score: '4,4',
    },
    {
      pic: '/imgs/pwa/img-6.png',
      name: 'Infinity Slots - Casino Games',
      describe: 'Murka Games Limited',
      score: '4,5',
    },
  ];
  let html = ``;

  data.forEach((d) => {
    html += `<div class="flex flex-1 gap-3 overflow-hidden flex-none">
            <img src="${d.pic}" alt="" class="h-14 w-14 rounded-lg" />
            <div class="text-3.5 text-black ml-1">
              <div class="whitespace-nowrap">${d.name}</div>
              <div class="whitespace-nowrap">${d.describe}</div>
              <div class="whitespace-nowrap">
                <div class="inline-flex items-center">
                  <span>${d.score}</span>
                  <img src="/imgs/pwa/star-black.svg" alt="" srcset="" class="w-3 ml-1" />
                </div>
              </div>
            </div>
          </div>`;
  });
  dom.innerHTML = html;
}

/** 加载弹窗 */
function createProgressPopup(callback?: () => void) {
  // 单例管理
  const overlayId = 'progress-overlay';
  let overlay = document.getElementById(overlayId);
  const progressBar = overlay?.querySelector('.progress-inner');
  let intervalId: number | undefined;
  let startTime: number | undefined;

  // 如果已存在则重置
  if (overlay) {
    clearInterval(intervalId);
    progressBar.style.width = '0%';
    startTime = Date.now();
    startProgress();
    return () => closePopup();
  }

  // 创建遮罩层
  overlay = document.createElement('div');
  overlay.id = overlayId;
  overlay.className = 'fixed inset-0 bg-black bg-opacity-50 z-auto';

  // 创建弹窗容器
  const popup = document.createElement('div');
  popup.className = 'absolute top-1/2 left-0 right-0 mx-auto -translate-y-1/2 w-1/2';

  // 弹窗内容
  const card = document.createElement('div');
  card.className = 'bg-white rounded-lg shadow-xl p-6 space-y-4';

  const text = document.createElement('div');
  text.className = 'text-gray-700 font-medium text-center';
  text.textContent = '环境监测中...';

  const progressContainer = document.createElement('div');
  progressContainer.className = 'h-2 bg-gray-200 rounded-full overflow-hidden';

  const progressInner = document.createElement('div');
  progressInner.className = 'progress-inner h-full bg-blue-500 transition-all duration-1000 ease-linear';
  progressInner.style.width = '0%';

  // 组装元素
  progressContainer.appendChild(progressInner);
  card.appendChild(text);
  card.appendChild(progressContainer);
  popup.appendChild(card);
  overlay.appendChild(popup);
  document.documentElement.appendChild(overlay);

  // 启动进度
  startTime = Date.now();
  startProgress();

  function startProgress() {
    const _second = 20000;
    intervalId = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / _second * 100, 100);

      progressInner.style.width = `${progress}%`;

      // 每秒执行回调（每100ms更新，但每秒只触发一次回调）
      if (typeof callback === 'function' && elapsed % 1000 < 100) {
        callback(Math.floor(progress));
      }

      if (progress >= 100) {
        closePopup();
      }
    }, 100);
  }

  function closePopup() {
    clearInterval(intervalId);
    overlay.remove();
  }

  // 返回关闭方法
  return closePopup;
}
